#include ".\File.h"
#include <cstdio>
#include <vector>
#include <Common\String.h>
#include <Common\Log.h>
using namespace std;

extern cLog Log;

string GetLine( FILE *file, int delim = '\n' )
{
	int c;
	string result;
	while( ( c = fgetc( file ) ) != EOF && c != delim )
	{
		result += ( char )c;
	}
	if( result == "" && c == EOF )
		return "EOF";
	return result;
}

string GetFile( FILE *file )
{
	int c;
	string result;
	while( ( c = fgetc( file ) ) != EOF )
	{
		result += ( char )c;
	}
	return result;
}

bool _ParseFile( FILE *file, map< string, map< string, string > > &document )
{
	string line;
	string curr_section = "global";

	Log.Debug( "_ParseFile has been started.\n" );

	document.clear();

	do
	{
		document.insert( make_pair( curr_section, map< string, string >() ) );
		while( true )
		{
			line = Trim( GetLine( file ) );
			Log.Debug( "Next line: %s\n", line.c_str() );
			if( line == "" )
				continue;
			if( line == "EOF" )
				break;
			if( line[ 0 ] == '[' )
			{
				curr_section = Trim( Split( Split( line, "[" )[ 1 ], "]" )[ 0 ] );
				Log.Debug( "New section: %s\n", curr_section.c_str() );
				break;
			}
			if( line[ 0 ] == ';' )
				continue;
			vector< string > temp = Split( line, "=" );
			if( temp.size() < 2 )
			{
				Log.Debug( "Line doesn't contains an equal sign: %s\n", line.c_str() );
				return false;
			}
			string variable = ToLower( Trim( temp[ 0 ] ) );
			temp.erase( temp.begin() );
			string value = Trim( Concat( temp, "=" ) );
			Log.Debug( "Variable: %s\nValue: %s\n", variable.c_str(), value.c_str() );
			document[ curr_section ].insert( make_pair( variable, value ) );
		} 
	} while( line != "EOF" );

	Log.Debug( "_ParseFile has been finished.\n" );

	return true;
}

bool ParseFile( const char path[], map< string, map< string, string > > &document )
{
	FILE *language_file = fopen( path, "rt" );
	if( language_file == NULL )
		return false;
	bool result = _ParseFile( language_file, document );
	fclose( language_file );
	return result;
}
